package com.hook.analyse.xp;
import de.robv.android.xposed.*;
import de.robv.android.xposed.callbacks.*;
import com.hook.analyse.util.*;
import com.hook.analyse.*;
import com.hook.analyse.model.*;
import java.util.*;
import java.lang.reflect.*;
import com.alibaba.fastjson.*;
import java.io.*;

public class HookMain implements IXposedHookLoadPackage
{

    /**
     * 包加载时候的回调
     */
    @Override
    public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable
	{
		String packageName=lpparam.packageName;
		HDb hdb=HDb.getInstance(Config.hookEventPath);
		List<HookEventBean> dataBean=hdb.read(HookEventBean.class);
		for (HookEventBean hook : dataBean)
		{

			if (hook.getPackageName().equals(packageName))
			{
				XposedBridge.log("加载:" + hook.getPackageName());
				Class<?> a1=XposedHelpers.findClass(hook.getClassPath().trim(), lpparam.classLoader);

				Method[] methods=a1.getDeclaredMethods();

				for (final Method m:methods)
				{
					if (m.getName().equals(hook.getMethod().trim()))
					{

						Object[] objs=new Object[m.getParameterTypes().length + 1];
						System.arraycopy(m.getParameterTypes(), 0, objs, 0, m.getParameterTypes().length);
						objs[objs.length - 1] = new XC_MethodHook(){

							@Override
							protected void beforeHookedMethod(MethodHookParam param) throws Throwable
							{

							    XposedBridge.log("---------------开始"+getMethod(m)+"----------------");
								try
								{
									XposedBridge.log(m.getName() + "-前置拦截:" + JSON.toJSONString(param.args));
								}
								catch (Throwable e)
								{
									XposedBridge.log(m.getName() + ":" + e.getMessage());
								}
							}

							@Override
							protected void afterHookedMethod(MethodHookParam param) throws Throwable
							{
								try
								{
									XposedBridge.log(m.getName() + "-后置拦截:" + JSON.toJSONString(param.getResult()));
								}
								catch (Throwable e)
								{
									XposedBridge.log(m.getName() + ":" + e.getMessage());

								}

								
								XposedBridge.log("-----调用堆栈信息开始--------");
							 	XposedBridge.log(new Exception());
								XposedBridge.log("-----调用堆栈信息结束--------");
							    XposedBridge.log("----------------结束---------------");

							}

						};
						XposedHelpers.findAndHookMethod(a1, m.getName(), objs);

					}

				}

			}

		}

	}




	public String getMethod(Method m){
		
		String res=m.getName()+"====";
		Class[] cl=m.getParameterTypes();
		for(Class c :cl){
			res+=c.getName()+" ";
		}
		return res;
		
	}
}
